package com.ypf.rpc.factory;

import com.ypf.rpc.manager.register.pojo.RegisterInfo;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RegisterFactory {

    // 保存所有Service的集合
    public static final List<RegisterInfo> registerFactory = new ArrayList<>();

    private Object Lock = new Object();

    // 添加服务进工厂
    public void addServer(Channel channel, String serverName, InetSocketAddress inetSocketAddress){

        synchronized (Lock){
            for (RegisterInfo registerInfo : registerFactory) {
                if (registerInfo.getServerName().equals(serverName)&&registerInfo.getInetSocketAddress().equals(inetSocketAddress)){
                    throw new RuntimeException("服务注册失败:注册中心已存在相同名称和相同ip+port的服务");
                }
            }
            RegisterInfo registerInfo = new RegisterInfo(channel,serverName,inetSocketAddress);
            registerFactory.add(registerInfo);
        }

        System.out.println("========= 新的服务器注册成功:"+serverName);

        for (RegisterInfo registerInfo : registerFactory) {
            System.out.println("当前已注册的服务:"+registerInfo.getServerName()+" 端口号:"+registerInfo.getInetSocketAddress().getPort()
                    +" Channel:"+registerInfo.getChannel());
        }
        System.out.println("=============================================");
    }

    // 从工厂中删除服务
    public void  removeServer(Channel channel){

        for (int i = 0; i < registerFactory.size(); i++) {
            if (registerFactory.get(i).getChannel().equals(channel)){
                RegisterInfo remove = registerFactory.remove(i);// 只要channel相同都删除 不管服务名
                i=i-1;
                System.out.println("xxxxxxx 服务器移除成功:"+remove.getServerName());
            }
        }

        for (RegisterInfo registerInfo : registerFactory) {
            System.out.println("当前已注册的服务:"+registerInfo.getServerName());
        }
    }

}
